package mqttser

import (
	"encoding/json"
	"fmt"
	"time"
	"webSer/memdb"

	mqtt "github.com/eclipse/paho.mqtt.golang"
)

var MC mqtt.Client

type MqttMes struct {
	ClientID string `json:"clientID"`
	Power    int    `json:"Power,omitempty"`
}

//收到消息消息的回调
var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	Topic := msg.Topic()
	TopicLen := len(Topic)
	if TopicLen < 4 {
		fmt.Println("Topic错误.")
		fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
	}
	clientTopic := "$SYS/broker/connection/clients/"
	if TopicLen > len(clientTopic) && clientTopic == Topic[:len(clientTopic)] {
		type ClientPub struct {
			ClientID  string `json:"clientID"`
			Online    bool   `json:"online"`
			Timestamp string `json:"timestamp"`
		}
		cobj := new(ClientPub)
		err := json.Unmarshal(msg.Payload(), &cobj)
		if err != nil {
			fmt.Println("解码错误:", err)
			fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
		}
		cisTrue := memdb.MqttClient.FindCid(cobj.ClientID)
		if cisTrue {
			memdb.MqttClient.EditLine(cobj.ClientID, cobj.Online)
		} else {
			memdb.MqttClient.Add(cobj.ClientID, "", cobj.Online, "")
		}
		memdb.MqttDBList.SetLine(cobj.ClientID, cobj.Online)
		return
	}
	cobj := new(MqttMes)
	err := json.Unmarshal(msg.Payload(), &cobj)
	if err != nil {
		fmt.Println("解码错误:", err)
		fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
		return
	}
	memdb.MqttClient.SetMesTime(cobj.ClientID, time.Now().Unix())
	memdb.MqttDBList.Add(cobj.ClientID, msg.Topic(), string(msg.Payload()), true, time.Now().Unix())
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	fmt.Println("Connected")
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	fmt.Printf("Connect lost: %v", err)
}

func MqttSerInit() {
	var broker = "127.0.0.1"
	var port = 183
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
	opts.SetClientID("go_mqtt_client")
	opts.Username = "admin"
	opts.Password = "admin123456"
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	MC = client
	sub(client)
}

func Publish(topic string, jsonStr interface{}) {
	fmt.Println("topic:", topic)
	fmt.Println("jsonStr:", jsonStr)
	b, err := json.Marshal(jsonStr)
	if err != nil {
		fmt.Println("JSON ERR:", err)
	}
	token := MC.Publish(topic, 0, false, string(b))
	token.Wait()
}

func sub(client mqtt.Client) {
	topic := "#"
	token := client.Subscribe(topic, 1, nil)
	token.Wait()
	fmt.Println("topic", topic)
}
